/**
 * Copyright 2007-2008. Chongqing First Information & Network Co., Ltd. All
 * rights reserved. <a>http://www.cqfirst.com.cn</a>
 */
package com.cqcis.uip.base.framework.xml.codec;

import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;

import com.cqcis.uip.base.framework.utils.StringUtil;
import com.cqcis.uip.base.framework.utils.XmlParseUtil;
import com.cqcis.uip.base.framework.xml.XMLDecoder;


/**
 * @author huangmy
 * @date   2007-12-4
 */
public abstract class AbstractXmlDecoder implements XMLDecoder {
	public Object decode(String xml) throws Exception {
		Document document = XmlParseUtil.get(xml);
		
		return doDecode(document);
	}
	
	public Object decode(Document document) throws Exception {
		return doDecode(document);
	}
	
	/**
	 * 获取文档的根节点
	 * @param document
	 * @return
	 */
	protected Element getRootElement(Document document) {
		return XmlParseUtil.getRootElement(document);
	}
	
	/**
	 * 获取指定节点上的属性值
	 * @param element
	 * @param attributeName
	 * @return
	 */
	protected String getAttributeValue(Element element, String attributeName) {
		return XmlParseUtil.getAttributeValue(element, attributeName);
	}
	
	/**
	 * 获取节点名称
	 * @param element
	 * @return
	 */
	protected String getElementName(Element element) {
		return XmlParseUtil.getElementName(element);
	}
	
	/**
	 * 获取节点全名
	 * @param element
	 * @return
	 */
	protected String getElementQualifiedName(Element element) {
		return XmlParseUtil.getElementQualifiedName(element);
	}
	
	/**
	 * 获取节点文本值
	 * @param element
	 * @return
	 */
	protected String getElementTextTrim(Element element) {
		return XmlParseUtil.getElementTextTrim(element);
	}
	
	/**
	 * 获取节点指定名称的子节点
	 * @param element
	 * @param childName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<Element> getChildElements(Element element, String childName) {
		return XmlParseUtil.getChildElements(element, childName);
	}
	
	/**
	 * 获取节点指定名称的子节点
	 * @param element
	 * @param childName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected Element getChildElement(Element element, String childName) {
		if (element == null || !StringUtil.hasText(childName)) {
			throw new NullPointerException("the element or childName can't be null.");
		}
		return XmlParseUtil.getChildElement(element, childName);
	}
	
	/**
	 * 返回节点的子节点集
	 * @param element
	 * @param childName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected Map<String, Element> getChildElementMap(Element element) {		
		return XmlParseUtil.getChildElementMap(element);
	}
	
	/**
	 * 解析XML文件
	 * @param xml
	 * @return
	 */
    public abstract Object doDecode(Document document);
}
